package com.tofu.citcounter;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.io.*;

public class AssetDatabaseOpenHelper {
	private static final String DB_PATH = "/data/data/com.tofu.citcounter/databases/";
	private static final String DB_NAME = "counter.sqlite";
    
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_PRICE = "price";
    public static final String COLUMN_COLOR = "color";
    public static final String COLUMN_NUMBER = "number";

    private Context context;
    private SQLiteDatabase database;
 
    public AssetDatabaseOpenHelper(Context context) {
        this.context = context;
    }
 
    public void openDatabase() {
        File dbDir = context.getDatabasePath(DB_PATH);
        dbDir.mkdirs();
        File dbFile = new File(dbDir, DB_NAME);

        if (!dbFile.exists()) {
            try {
                copyDatabase(dbFile);
            } catch (IOException e) {
                throw new RuntimeException("Error creating source database", e);
            }
        }
 
        this.database = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY);
    }
 
    private void copyDatabase(File dbFile) throws IOException {
        InputStream is = context.getAssets().open(DB_NAME);
        OutputStream os = new FileOutputStream(dbFile);
 
        byte[] buffer = new byte[1024];
        while (is.read(buffer) > 0) {
            os.write(buffer);
        }
 
        os.flush();
        os.close();
        is.close();
    }

    public Cursor selectAll() {
        return this.database.rawQuery("SELECT * FROM buildings", null);
    }

    public void closeDatabase() {
        this.database.close();
    }
}
